import QueryRules from './eums'

/**
 * HandleStrings
 */
class HandleStrings {
  public orgin: string
  public h_type: number[]

  constructor(orgin: string, h_type: number[]) {
    this.orgin = orgin
    this.h_type = h_type
  }

  private trim() {
    return this.orgin.trim()
  }

  private toLowerCase() {
    return this.orgin.toLowerCase()
  }

  /**
   * Handles string transformations based on specified query rules.
   * @returns The transformed string or original string if no transformations are specified.
   */
  handle(): string {
    if (this.h_type.length === 0) {
      return this.orgin
    }

    for (let i = 0; i < this.h_type.length; i++) {
      switch (this.h_type[i]) {
        case QueryRules.LTWhitespace:
          this.orgin = this.trim()
          break
        case QueryRules.IgnoreCase:
          this.orgin = this.toLowerCase()
          break
        default:
          break
      }
    }
    return this.orgin
  }
}

/**
 * Escapes special characters in a string to be used in a regular expression.
 * @param str - The input string to be escaped.
 * @returns The escaped string.
 */
function escapeRegExp(str: string) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

function getHttpOrHttps(url: string) {
  const httpRegex =
    /https?:\/\/(?:[-\w.]|(?:%[\da-fA-F]{2}))+(?::\d+)?(?:\/[-\w.\/?%&=-]*)?/g
  return url.match(httpRegex)
}

async function copyToClipboard(text: string) {
  try {
    await navigator.clipboard.writeText(text)
    console.group(
      '%cText copied to clipboard successfully!',
      'background-color: green; color: #ffffff;',
    )
  } catch (err) {
    throw new Error('Failed to copy text: ' + err)
  }
}

export { HandleStrings, escapeRegExp, getHttpOrHttps, copyToClipboard }
